<template>
  <div v-loading="loading" class="category-manage">
    <!-- tree start -->
    <div class="category-container">
      <div class="handle-box">
        <div class="filter-input">
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            size="small"
          />
        </div>
        <el-button
          type="text"
          round
          icon="el-icon-plus"
          class="add-btn"
          @click="add({isAddLevel1:true})"
        >新增根类目
        </el-button>
      </div>
      <div class="list-container">
        <el-tree
          ref="categoryTree"
          :data="treeData"
          :props="treeProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :highlight-current="true"
          node-key="id"
          default-expand-all
          accordion
          @node-click="handleTree"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ node.label }}</span>
            <el-button
              v-show="node.level<=2"
              type="text"
              class="add-btn"
              size="small"
              icon="el-icon-plus"
              @click.stop="add({node, data})"
            >
              子类目</el-button>
          </span>
        </el-tree>
      </div>
    </div>
    <!-- tree end -->

    <!-- form start -->
    <div class="form-container app-main-content-box">
      <div v-if="mode==='edit'&&activeTreeNode||mode==='add'&&(activeTreeNode||isAddLevel1)">
        <div>
          <AppMainTitle :title="mode === 'add' ? activeTreeNode?'新增子类目':'新增根类目' : '编辑类目'" />
        </div>
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="130px"
          size="small"
        >
          <el-form-item
            v-if="mode === 'edit' && activeTreeNode && activeTreeNode.level !== 1"
            label="上级类目："
          >{{ activeTreeNode.parent.data.title }}
          </el-form-item>
          <el-form-item
            v-if="mode === 'add' && activeTreeNode"
            label="上级类目："
          >{{ activeTreeNode.data.title }}
          </el-form-item>
          <el-form-item label="类别名称：" prop="title">
            <el-input
              v-model.trim="form.title"
              class="w-300-h-32"
              maxlength="10"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="类别编码：">
            <el-input
              v-model="form.categoryNo"
              class="w-300-h-32"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="类目商品属性：" prop="specList">
            <el-card
              v-for="(item, index) in form.specList"
              :key="'spec-' + index"
              class="spec-card"
            >
              <div slot="header" class="clearfix">
                <span>{{ item.title }}</span>
                <el-button
                  style="float: right"
                  type="text"
                  @click="delSpec(index)"
                >删除
                </el-button>
              </div>
              <el-form-item
                :prop="'specList.' + index + '.attrList'"
                :rules="rules.attrList"
              >
                <el-tag
                  v-for="(tagItem, tagIndex) in item.attrList"
                  :key="'attr-' + tagIndex"
                  :disable-transitions="false"
                  closable
                  @close="closeAttr(item.attrList, tagIndex)"
                >{{ tagItem.title }}
                </el-tag>
                <div>
                  <el-input
                    v-if="item.inputVisible"
                    ref="saveAttrInput"
                    v-model="item.inputValue"
                    class="w-450-h-32"
                    size="small"
                    placeholder="请输入属性选项"
                    maxlength="30"
                    show-word-limit
                    @keyup.enter.native="addAttr(item)"
                    @blur="addAttr(item)"
                  />
                  <el-button
                    v-else
                    size="small"
                    style="height: 32px"
                    @click="showAttrInput(item)"
                  >+ 增加类目属性选项
                  </el-button>
                </div>
              </el-form-item>
            </el-card>

            <el-input
              v-if="specInputVisible"
              ref="saveSpecInput"
              v-model.trim="form.specInputValue"
              class="w-300-h-32"
              size="small"
              placeholder="请输入属性名"
              maxlength="10"
              show-word-limit
              @keyup.enter.native="addSpec"
              @blur="addSpec"
            />

            <el-button
              v-else
              type="text"
              icon="el-icon-plus"
              style="height: 32px"
              @click="showSpecInput"
            >增加类目商品属性
            </el-button>
          </el-form-item>
          <el-form-item label="类目商品参数：">
            <el-card v-if="form.paramList.length > 0" class="spec-card">
              <el-tag
                v-for="(paramItem, paramIndex) in form.paramList"
                :key="'param-' + paramIndex"
                :disable-transitions="false"
                closable
                @close="closeParam(paramIndex)"
              >{{ paramItem }}
              </el-tag>
              <div>
                <el-input
                  v-if="paramInputVisible"
                  ref="saveParamInput"
                  v-model.trim="form.paramInputValue"
                  class="w-300-h-32"
                  size="small"
                  placeholder="请输入参数"
                  maxlength="10"
                  show-word-limit
                  @keyup.enter.native="addParams"
                  @blur="addParams"
                />
                <el-button
                  v-else
                  size="small"
                  style="height: 32px"
                  @click="showParamInput"
                >+ 增加类目商品参数
                </el-button>
              </div>
            </el-card>

            <div v-else>
              <el-input
                v-if="paramInputVisible"
                ref="saveParamInput"
                v-model.trim="form.paramInputValue"
                class="w-300-h-32"
                size="small"
                placeholder="请输入参数"
                maxlength="10"
                show-word-limit
                @keyup.enter.native="addParams"
                @blur="addParams"
              />
              <el-button
                v-else
                type="text"
                icon="el-icon-plus"
                style="height: 32px"
                @click="showParamInput"
              >增加类目商品参数
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" round @click="submit">保 存</el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="reset"
            >重 置
            </el-button>
            <el-button
              v-show="mode === 'edit'"
              round
              @click="del"
            >删 除
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="empty-form-tips">
        请选择类目
      </div>

    </div>
    <!-- form end -->
  </div>
</template>

<script>
import {
  categoryDetail,
  categoryTree,
  addCategory,
  delCategory,
  updateCategory,
  getSpecId,
  getAttrId
} from '@/views/wxaMallModule/api/category'

export default {
  data() {
    return {
      // 校验规则相关
      rules: {
        title: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
        categoryNo: [
          { required: true, message: '请输入类别编码', trigger: 'blur' }
        ],
        attrList: [
          {
            type: 'array',
            required: true,
            message: '请至少设置一种属性选项'
            // trigger: "change",
          }
        ]
      },
      // 配置
      treeProps: {
        label: 'title'
      },
      // 状态
      loading: false,
      paramInputVisible: false,
      specInputVisible: false,
      isAddLevel1: false,
      // 数据
      filterText: '',
      treeData: [],
      mode: 'add',
      activeTreeNode: null,
      activeTreeData: null,
      form: {
        categoryNo: '',
        icon: '',
        parentId: 0,
        parentIds: '',
        ranking: '',
        paramList: [],
        specList: [],
        title: '',
        specInputValue: '',
        paramInputValue: ''
      }
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    // 获取tree列表
    fetchData() {
      this.loading = true
      categoryTree()
        .then((res) => {
          this.treeData = res.data
          this.$nextTick(() => {
            if (this.activeTreeData) {
              this.$refs.categoryTree.setCurrentKey(this.activeTreeData.id)
            }
          })
        })
        .catch((err) => {
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取详情
    getDetail(id) {
      categoryDetail({ categoryId: id })
        .then((res) => {
          res.data.specList.map((v) => {
            v.inputVisible = false
            v.inputValue = ''
          })
          this.form = res.data
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        })
        .catch((err) => {
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取

    /**
     * 按钮组
     */
    // 新增类目
    add({ node, data, isAddLevel1 = false }) {
      this.mode = 'add'
      if (!isAddLevel1) {
        this.isAddLevel1 = false
        this.activeTreeNode = node
        this.activeTreeData = data
        this.defaultForm(false)
        this.form.parentId = data.id
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      } else {
        this.isAddLevel1 = true
        this.defaultForm(true)
      }
    },

    // 点击tree
    handleTree(data, node) {
      console.log('handleTree', data, node)
      if (data.id === this.form.id) {
        // this.$refs.categoryTree.setCurrentKey(null)
        // this.defaultForm(true)
        return
      }
      this.loading = true
      this.mode = 'edit'
      this.activeTreeNode = node
      this.activeTreeData = data
      this.getDetail(data.id)
    },

    // 显示specInput
    showSpecInput() {
      this.specInputVisible = true
      this.$nextTick(() => {
        this.$refs.saveSpecInput.$refs.input.focus()
      })
    },

    // 删除spec
    delSpec(index) {
      this.form.specList.splice(index, 1)
    },

    // 新增spec
    addSpec() {
      const inputValue = this.form.specInputValue
      if (inputValue) {
        const flag = this.form.specList.some((v) => {
          if (inputValue === v.title) {
            return true
          }
        })
        if (flag) {
          this.specInputVisible = false
          this.form.specInputValue = ''
          return
        }
        getSpecId({ title: inputValue })
          .then((res) => {
            this.form.specList.push({
              title: inputValue,
              id: res.data,
              attrList: [],
              inputVisible: false,
              inputValue: ''
            })
            this.specInputVisible = false
            this.form.specInputValue = ''
          })
          .catch((err) => {
          })
          .finally(() => {
          })
      } else {
        this.specInputVisible = false
        this.form.specInputValue = ''
      }
    },

    // 显示attrInput
    showAttrInput(item) {
      // 其它移除
      this.form.specList.forEach((v) => {
        if (v.id != item.id) {
          v.inputVisible = false
        }
      })
      // 当前激活
      item.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveAttrInput[0].$refs.input.focus()
      })
    },

    // 新增attr
    addAttr(row) {
      const inputValue = row.inputValue
      if (inputValue) {
        const flag = row.attrList.some((v) => {
          if (inputValue === v.title) {
            return true
          }
        })
        if (flag) {
          row.inputVisible = false
          row.inputValue = ''
          return
        }
        getAttrId({ specId: row.id, title: inputValue })
          .then((res) => {
            row.attrList.push({
              title: inputValue,
              id: res.data
            })
            // row.inputVisible = false;
            row.inputValue = ''
          })
          .catch((err) => {
          })
          .finally(() => {
          })
      } else {
        row.inputVisible = false
        row.inputValue = ''
      }
    },

    // 关闭attr
    closeAttr(row, index) {
      row.splice(index, 1)
    },

    // 显示attrInput
    showParamInput() {
      this.paramInputVisible = true
      this.$nextTick(() => {
        this.$refs.saveParamInput.$refs.input.focus()
      })
    },

    // 新增商品参数
    addParams() {
      const inputValue = this.form.paramInputValue
      if (inputValue) {
        this.form.paramList.push(inputValue)
        this.form.paramList = [...new Set(this.form.paramList)]
        this.form.paramInputValue = ''
      } else {
        this.paramInputVisible = false
        this.form.paramInputValue = ''
      }
    },

    // 关闭参数
    closeParam(index) {
      this.form.paramList.splice(index, 1)
    },

    // 保存
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.id) {
            updateCategory(this.form)
              .then((res) => {
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
              })
              .finally(() => {
                this.loading = false
              })
          } else {
            addCategory(this.form)
              .then((res) => {
                this.fetchData()
                this.$notify({
                  title: '成功',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                // 清空数据
                this.form = {
                  categoryNo: '',
                  icon: '',
                  parentId: this.form.parentId,
                  parentIds: this.form.parentIds,
                  ranking: '',
                  paramList: [],
                  specList: [],
                  title: '',
                  specInputValue: '',
                  paramInputValue: ''
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },

    // 删除
    del() {
      this.$confirm(
        `您确定要删除类目：${this.activeTreeData.title}，是否继续?`,
        '温馨提示',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
          roundButton: true
        }
      ).then(() => {
        this.loading = true
        delCategory({ categoryId: this.form.id })
          .then((res) => {
            this.$refs.categoryTree.remove(this.activeTreeData)
            this.defaultForm()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
          })
          .catch((err) => {
          })
          .finally(() => {
            this.loading = false
          })
      })
    },

    // 重置
    reset() {
      this.getDetail(this.form.id)
    },
    /**
     * 状态组
     */
    /**
     * 方法组
     */
    // 筛选tree
    filterNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },

    // 默认数据
    defaultForm(clearActive = true) {
      if (clearActive) {
        this.activeTreeNode = null
        this.activeTreeData = null
      }
      this.mode = 'add'
      this.specInputVisible = ''
      this.paramInputVisible = ''
      this.form = {
        categoryNo: '',
        icon: '',
        parentId: 0,
        parentIds: '',
        ranking: '',
        paramList: [],
        specList: [],
        title: '',
        specInputValue: '',
        paramInputValue: ''
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/*容器*/
.category-manage {
  display: flex;

  .category-container {
    margin-right: 10px;
  }

  .form-container {
    flex: 1;
  }
}

/* 类目 */
.category-container {
  background-color: #fff;
  padding: 24px 0 10px;
  border-radius: 5px;

  .handle-box {
    padding: 0 10px;
  }

  .list-container {
    overflow: auto;
    height: calc(100vh - 184px);
    padding: 0 10px;
    font-size: 14px;
  }
  .custom-tree-node{
    width: 100%;
    .add-btn{
      margin-left: 2px;
      visibility: hidden;
      height: 32px;
    }
    &:hover{
      .add-btn{
        visibility: visible;
      }
  }
  }
}

/* 表单 */
.form-container {
  .w-300-h-32 {
    width: 300px;
    height: 32px;
  }

  .w-450-h-32 {
    width: 450px;
    height: 32px;
  }

  .spec-card {
    width: 600px;
    margin-bottom: 10px;

    ::v-deep .el-card__header {
      padding: 5px 20px;
    }

    .el-tag {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}

//空标签
.empty-form-tips{
  margin: 100px 0;
  text-align: center;
  font-size: 14px;
  color:#606266;
}
</style>
